package com.wnxy.b_pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 */
public class App1ThreadPool {

    //线程池核心线程数
    private static final int CORE_POOL_SIZE = 5;
    // 线程池中最大线程数
    private static final int MAX_POOL_SIZE = 10;
    // 当线程池中线程数大于核心线程数时候，多余的线程最大存活时间，这里指定为100秒
    private static final int KEEP_ALIVE_TIME = 100;
    // 队列大小
    private static final int CAPCITY = 100;

    public static void main(String[] args) {

        // 创建线程池
        ThreadPoolExecutor executor =
                new ThreadPoolExecutor(
                        CORE_POOL_SIZE, // 核心线程：5
                        MAX_POOL_SIZE,  // 最大线程：10
                        KEEP_ALIVE_TIME, // 时间
                        TimeUnit.SECONDS, // 时间单位
                        new ArrayBlockingQueue<>(CAPCITY),
                        new ThreadPoolExecutor.CallerRunsPolicy()
                );
        // 运行线程
        for (int i = 0; i < 10; i++) {
            executor.execute(()->{
                System.out.println(Thread.currentThread().getName() + "start:");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "end:");
            });
        }
        // 关闭线程池
        executor.shutdown();
        while (!executor.isShutdown()) {}
        System.out.println(" Finish All");
    }
}
